<template>
    <div>
        <el-container>
            <el-header>图片处理</el-header>
            <el-main>
                <el-row :gutter="20">
                    <el-col :span="2" :offset="2">
                        <span>待处理的图片</span>
                    </el-col>
                    <el-col :span="6">
                        <el-upload action="#" list-type="picture-card" ref="upload" :limit="1" :data="imgdata"
                                   :auto-upload="false" :before-upload="beforeUpload"
                                   :on-preview="handlePictureCardPreview"
                                   :on-change="beforeUpload" :on-remove="handleRemove">
                            <i class="el-icon-plus"></i>
                        </el-upload>
                    </el-col>
                    <el-col :span="2" :offset="2">
                        <span>水印添加后效果</span>
                        <br><br>
                        <span v-show="buttonVisible">点击图片可放大</span>
                        <br><br>
                        <span v-show="buttonVisible" style="color: red">共生成{{afterHandleList.length}}张图片</span>
                    </el-col>
                    <el-col :span="6">
                        <div class="demo-image__preview">
                            <el-image style="width: 200px;" :src="afterHandle" :preview-src-list="afterHandleList">
                                <div slot="error" class="image-slot">
                                    <i class="el-icon-picture-outline"></i>
                                    <span>等待图片上传</span>
                                </div>
                            </el-image>
                        </div>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="2" :offset="2">
                        <span>待添加的水印文字</span>
                    </el-col>
                    <el-col :span="4" :offset="1">
                        <el-input v-model="imgdata.waterMarkContent" placeholder="水印内容"></el-input>
                    </el-col>
                    <el-col :span="4" :offset="5">
                        <el-button :disabled="progressVisible" size="small" type="primary" @click="download" v-show="buttonVisible">{{downloadTxt}}</el-button>
                        <el-button size="small" type="warning" @click="clearUploadedImage" v-show="buttonVisible">重置
                        </el-button>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="4" :offset="5">
                        <el-button size="small" type="success" @click="submitUpload" v-show="!buttonVisible">添加水印
                        </el-button>
                    </el-col>
                </el-row>
                <el-dialog :visible.sync="dialogVisible">
                    <img width="100%" :src="dialogImageUrl" alt="">
                </el-dialog>
            </el-main>
        </el-container>
    </div>
</template>

<script>
    import {
        TypeFile
    } from 'get-real-file-type';
    import JSZip from 'jszip';
    import FileSaver from 'file-saver';

    export default {
        name: 'ImageUpload',
        data() {
            return {
                dialogImageUrl: '',
                dialogVisible: false,
                buttonVisible: false,
                afterHandle: '',
                afterHandleList: [],
                afterHandleName: [],
                imgdata: {
                    "fileInputName": 'file',
                    "waterMarkContent": ''
                },
                file: null,
                downloadTxt: '下载图片',
                progressVisible: false,
                progressPercentage: 0
            };
        },
        methods: {
            beforeUpload(file) {
                let typeFile = new TypeFile(file);
                let $this = this;
                $this.file = file.raw;
                typeFile.onParseEnd = function () {
                    if (this.isType(['image/jpeg', 'image/png', 'image/bmp', 'image/tiff'])) {
                        let isLt2M = file.size / 1024 / 1024 < 5;
                        if (!isLt2M) {
                            this.$message.error('上传图片大小不能超过 5MB!');
                            return false;
                        }
                        return true;
                    } else {
                        $this.$message.error('上传图片只能是 JPG/PNG/BMP/TIF 格式!');
                        return false;
                    }
                };
                typeFile.onParseError = function () {
                    $this.$message.error('上传图片无法解析!');
                    return false;
                };
                typeFile.start();
            },
            // 原用于on-success
            // 原handleSuccess，增加了obj参数替代this
            afterUpload(res, obj) {
                obj.$message.success(res.msg);
                let imsList = [];
                let imgName = [];
                for (let i = 0; i < res.data.length; i++) {
                    let data = res.data[i];
                    imsList[i] = "data:image/" + data.suffix + ";base64," + data.base64str;
                    imgName[i] = data.imgname;
                    obj.afterHandle = imsList[0];
                }
                obj.afterHandleName = imgName;
                obj.afterHandleList = imsList;
                obj.buttonVisible = true;
                // 以服务的方式调用的 Loading 需要异步关闭
                obj.$nextTick(() => {
                    obj.$loading().close();
                });
            },
            handleRemove() {
                this.dialogImageUrl = '';
                this.dialogVisible = false;
                this.afterHandle = '';
                this.afterHandleList = [];
                this.imgdata.waterMarkContent = '';
                this.buttonVisible = false;
                this.file = null;
            },
            clearUploadedImage() {
                // this.$refs.upload.clearFiles();
                this.afterHandle = '';
                this.afterHandleList = [];
                this.afterHandleName = [];
                // this.imgdata.waterMarkContent = '';
                this.buttonVisible = false;
                // this.file = null;
            },
            handlePictureCardPreview(file) {
                this.dialogImageUrl = file.url;
                this.dialogVisible = true;
            },
            download() {
                // let imgList = this.afterHandleList;
                // let nameList = this.afterHandleName;
                // for (let i = 0; i < imgList.length; i++) {
                //     let alink = document.createElement("a");
                //     alink.href = imgList[i];
                //     alink.download = nameList[i];
                //     setTimeout(function () {
                //         alink.click();
                //         alink.remove();
                //     },1000)
                // }
                this.mergeZip()
            },
            mergeZip() {
                this.progressVisible = true
                let $this = this;
                $this.downloadTxt = "批量下载中，请稍后……"
                const zip = new JSZip();
                let imgsss = zip.folder("");
                let imgList = this.afterHandleList;
                let nameList = this.afterHandleName;
                for (let i = 0; i < imgList.length; i++) {
                    let resultBase64 = imgList[i].substring(imgList[i].indexOf(",") + 1);
                    imgsss.file(nameList[i], resultBase64, {base64: true});
                }
                setTimeout(() => {
                    zip.generateAsync({type: "blob"}, (metadata) => {
                        this.downloadTxt = `正在下载：${Number.parseInt(metadata.percent,0)}%`
                        if (metadata.percent >= 100) {
                            // 以服务的方式调用的 Loading 需要异步关闭
                            this.progressVisible = false
                            this.downloadTxt = "下载图片"
                        }
                    }).then(content => {
                        // 生成二进制流
                        FileSaver.saveAs(content, `水印${this.getCurrentTime()}.zip`); // 利用file-saver保存文件  自定义文件名
                    });
                }, 1500);
            },
            submitUpload() {
                let $this = this;
                let formdata = new FormData();
                formdata.append($this.imgdata.fileInputName, $this.file);
                formdata.append("fileInputName", $this.imgdata.fileInputName);
                formdata.append("waterMarkContent", $this.imgdata.waterMarkContent);
                $this.axios.post('/upload', formdata).then(res => {
                    $this.$options.methods.afterUpload(res.data, $this);
                });
                $this.$loading({
                    lock: true,
                    text: '上传中……',
                    spinner: 'el-icon-loading',
                    background: 'rgba(0, 0, 0, 0.7)'
                });
            },
            getCurrentTime() {
                //获取当前时间并打印
                let yy = new Date().getFullYear();
                let mm = new Date().getMonth() + 1;
                let dd = new Date().getDate();
                let hh = new Date().getHours();
                let mf = new Date().getMinutes() < 10 ? '0' + new Date().getMinutes() : new Date().getMinutes();
                let ss = new Date().getSeconds() < 10 ? '0' + new Date().getSeconds() : new Date().getSeconds();
                return yy + '/' + mm + '/' + dd + ' ' + hh + ':' + mf + ':' + ss;
            }
        }
    }
</script>

<style scoped>
    .el-row {
        margin-bottom: 20px;
    }
</style>
